// newapi/statusChangeLogRoutes.js
const express = require('express');
const router = express.Router();
const StatusChangeLog = require('../../models/newmodels/statusChangeLogSchema'); // 状态变更日志文档

// 创建一个新的状态变更记录
router.post('/statusChangeLogs', async (req, res) => {
  try {
    const statusChangeLog = new StatusChangeLog(req.body);
    await statusChangeLog.save();
    res.status(201).send({ code: '201', msg: '状态变更记录插入成功', data: statusChangeLog });
  } catch (error) {
    res.status(400).send({ code: '400', msg: '状态变更记录插入失败', data: error });
  }
});

// 获取所有状态变更记录
router.get('/statusChangeLogs', async (req, res) => {
  try {
    const statusChangeLogs = await StatusChangeLog.find().populate('machineId');
    res.status(200).send({ code: '200', msg: '查询数据成功', data: statusChangeLogs });
  } catch (error) {
    res.status(500).send({ code: '500', msg: '查询数据失败', data: error });
  }
});

// 更新单个状态变更记录
router.put('/statusChangeLogs/:id', async (req, res) => {
  try {
    const statusChangeLog = await StatusChangeLog.findByIdAndUpdate(req.params.id, req.body, { new: true, runValidators: true });
    if (!statusChangeLog) {
      return res.status(404).send({ code: '404', msg: '没有找到该状态变更记录', data: null });
    }
    res.status(200).send({ code: '200', msg: '更新状态变更记录成功', data: statusChangeLog });
  } catch (error) {
    res.status(400).send({ code: '400', msg: '更新状态变更记录失败', data: error });
  }
});

// 删除单个状态变更记录
router.delete('/statusChangeLogs/:id', async (req, res) => {
  try {
    const statusChangeLog = await StatusChangeLog.findByIdAndDelete(req.params.id);
    if (!statusChangeLog) {
      return res.status(404).send({ code: '404', msg: '没有找到要删除的状态变更记录', data: null });
    }
    res.status(200).send({ code: '200', msg: '状态变更记录删除成功', data: statusChangeLog });
  } catch (error) {
    res.status(500).send({ code: '500', msg: '状态变更记录删除失败', data: error });
  }
});

module.exports = router;